import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:lcapp/api/interface/home_api.dart';
import 'package:lcapp/api/request/response_data.dart';
import 'package:lcapp/data/xian_huo_data_entity.dart';
import 'package:lcapp/model/refresh/refresh.dart';
import 'package:lcapp/page/search/xianhuo_item.dart';
import 'package:lcapp/widget/asr_app_bar.dart';

class SearchXHPage extends StatefulWidget {
  final String searchValue;
  const SearchXHPage({Key? key, required this.searchValue}) : super(key: key);

  @override
  _SearchXHPageState createState() => _SearchXHPageState();
}

class _SearchXHPageState extends State<SearchXHPage> {
  int pageNum = 1;
  int pageSize  =10;
  List<XianHuoDataEntity> xianHuos = [];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getXianHuo();
  }

  getXianHuo()async{
    Map<String,dynamic> data = {
      'page':pageNum,
      'size':pageSize,
      'keyword':widget.searchValue
    };
    ResponseData res = await HomeAPI.getXianHuos(data);
    if(res.code==200){
      if(pageNum==1){
        xianHuos.clear();
      }
      List arr = res.data??[];
      for (var element in arr) {
        XianHuoDataEntity entity = XianHuoDataEntity().fromJson(element);
        xianHuos.add(entity);
      }
    }
    if(mounted){setState(() {
    });}
  }

  @override
  void didUpdateWidget(covariant SearchXHPage oldWidget) {
    // TODO: implement didUpdateWidget
    super.didUpdateWidget(oldWidget);
    if(oldWidget.searchValue != widget.searchValue){
      pageNum = 1;
      getXianHuo();
    }
  }

  @override
  Widget build(BuildContext context) {
    return EasyRefresh(
      header: myRefreshHeader(),
      footer: myRefreshFooter(),
      onRefresh: ()async{
        pageNum = 1;
        getXianHuo();
      },
      onLoad: ()async{
        pageNum++;
        getXianHuo();
      },
      child: AlignedGridView.count(
        padding: EdgeInsets.zero,
        itemCount: xianHuos.length,
        crossAxisCount: 2,
        crossAxisSpacing: 10.w,
        mainAxisSpacing: 10.w,
        // gridDelegate:
        // SliverStaggeredGridDelegateWithFixedCrossAxisCount(
        //   crossAxisCount: 2,
        //   staggeredTileBuilder: (index) {
        //     return StaggeredTile.fit(1);
        //   },
        //   crossAxisSpacing: 10.w,
        //   mainAxisSpacing: 10.w,
        // ),
        itemBuilder: (context,index){
          return XianHuoItem(entity: xianHuos[index], chooseFun: (){},);
        },
      ),
    );
  }
}
